<?php namespace testsacvoyage\storage;

use \ArrayIterator;

require_once 'testsacvoyage/storage/AbstractTest.php';
use testsacvoyage\storage\AbstractTest;

require_once 'sacvoyage/storage/Gateway.php';
use sacvoyage\storage\Gateway;

require_once 'sacvoyage/storage/Table.php';
use sacvoyage\storage\Table;

require_once 'sacvoyage/storage/Reducer.php';
use sacvoyage\storage\Reducer;

require_once 'sacvoyage/Object.php';
use sacvoyage\Object;




class ReducerTest extends AbstractTest {

	public function setUp() {
		$this->resetDatabase();	
		$this->fillDatabase();
	}

	
	public function testReduceAll() {
		$expected=array(new Object(array(
			'priority'=> 4
		)));
		$result=$this->reduceDocuments(new Object(array(
			'priority'=> '_min'
		)));
		$this->assertEquals($expected, $result);
	}
	
	public function testReduceGroupByType() {
		$expected=array(
			new Object(array(
				'type'=>'note',
				'priority'=>4
			)),
			new Object(array(
				'type'=>'book'
			)),
			new Object(array(
				'type'=>'idea'
			))			
		);
		$result=$this->reduceDocuments(new Object(array(
			'priority'=> '_min',
			'type'=>'_group'
		)));
		
		$this->_sort($expected);
		$this->_sort($result);
		$this->assertEquals($expected, $result);
	}
	
	
	private function _sort(&$array) {
		$array=array_map('serialize', $array);
		sort($array);
		$array=array_map('unserialize', $array);
	}	


	public function reduceDocuments($reduce) {
		return iterator_to_array( 
			new Reducer(
				new Table($this->getGateway(), 'alex_db_notes'),
				null,
				$reduce
			)
		);
	}

}

?>
